Completed
Push — master ( c898d2...a76502 )
by Rafael S.
08:20
created

WaveFileConverter.assureUncompressed_   A

Complexity

Conditions 4

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 4
1
/*
2
 * Copyright (c) 2017-2019 Rafael da Silva Rocha.
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining
5
 * a copy of this software and associated documentation files (the
6
 * "Software"), to deal in the Software without restriction, including
7
 * without limitation the rights to use, copy, modify, merge, publish,
8
 * distribute, sublicense, and/or sell copies of the Software, and to
9
 * permit persons to whom the Software is furnished to do so, subject to
10
 * the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be
13
 * included in all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
 *
23
 */
24
25
/**
26
 * @fileoverview The WaveFileConverter class.
27
 * @see https://github.com/rochars/wavefile
28
 */
29
30
import { changeBitDepth } from 'bitdepth';
31
import * as imaadpcm from 'imaadpcm';
32
import * as alawmulaw from 'alawmulaw';
33
import { unpackArray, unpackArrayTo } from 'byte-data';
34
import { WaveFileMetaEditor } from './wavefile-meta-editor';
35
import { truncateIntSamples } from './parsers/truncate-samples';
36
import { validateSampleRate } from './validators/validate-sample-rate';
37
import { resample } from './resampler';
38
39
/**
40
 * A class to convert wav files to other types of wav files.
41
 * @extends WaveFileMetaEditor
42
 * @ignore
43
 */
44
export class WaveFileConverter extends WaveFileMetaEditor {
45
46
  /**
47
   * Force a file as RIFF.
48
   */
49
  toRIFF() {
50
    this.fromExisting_(
51
      this.fmt.numChannels,
52
      this.fmt.sampleRate,
53
      this.bitDepth,
54
      unpackArray(this.data.samples, this.dataType));
55
  }
56
57
  /**
58
   * Force a file as RIFX.
59
   */
60
  toRIFX() {
61
    this.fromExisting_(
62
      this.fmt.numChannels,
63
      this.fmt.sampleRate,
64
      this.bitDepth,
65
      unpackArray(this.data.samples, this.dataType),
66
      {container: 'RIFX'});
67
  }
68
69
  /**
70
   * Encode a 16-bit wave file as 4-bit IMA ADPCM.
71
   * @throws {Error} If sample rate is not 8000.
72
   * @throws {Error} If number of channels is not 1.
73
   */
74
  toIMAADPCM() {
75
    if (this.fmt.sampleRate !== 8000) {
76
      throw new Error(
77
        'Only 8000 Hz files can be compressed as IMA-ADPCM.');
78
    } else if (this.fmt.numChannels !== 1) {
79
      throw new Error(
80
        'Only mono files can be compressed as IMA-ADPCM.');
81
    } else {
82
      this.assure16Bit_();
83
      /** @type {!Int16Array} */
84
      let output = new Int16Array(this.outputSize_());
85
      unpackArrayTo(this.data.samples, this.dataType, output);
86
      this.fromExisting_(
87
        this.fmt.numChannels,
88
        this.fmt.sampleRate,
89
        '4',
90
        imaadpcm.encode(output),
91
        {container: this.correctContainer_()});
92
    }
93
  }
94
95
  /**
96
   * Decode a 4-bit IMA ADPCM wave file as a 16-bit wave file.
97
   * @param {string} bitDepthCode The new bit depth of the samples.
98
   *    One of '8' ... '32' (integers), '32f' or '64' (floats).
99
   *    Optional. Default is 16.
100
   */
101
  fromIMAADPCM(bitDepthCode='16') {
102
    this.fromExisting_(
103
      this.fmt.numChannels,
104
      this.fmt.sampleRate,
105
      '16',
106
      imaadpcm.decode(this.data.samples, this.fmt.blockAlign),
107
      {container: this.correctContainer_()});
108
    if (bitDepthCode != '16') {
109
      this.toBitDepth(bitDepthCode);
110
    }
111
  }
112
113
  /**
114
   * Encode a 16-bit wave file as 8-bit A-Law.
115
   */
116
  toALaw() {
117
    this.assure16Bit_();
118
    /** @type {!Int16Array} */
119
    let output = new Int16Array(this.outputSize_());
120
    unpackArrayTo(this.data.samples, this.dataType, output);
121
    this.fromExisting_(
122
      this.fmt.numChannels,
123
      this.fmt.sampleRate,
124
      '8a',
125
      alawmulaw.alaw.encode(output),
126
      {container: this.correctContainer_()});
127
  }
128
129
  /**
130
   * Decode a 8-bit A-Law wave file into a 16-bit wave file.
131
   * @param {string} bitDepthCode The new bit depth of the samples.
132
   *    One of '8' ... '32' (integers), '32f' or '64' (floats).
133
   *    Optional. Default is 16.
134
   */
135
  fromALaw(bitDepthCode='16') {
136
    this.fromExisting_(
137
      this.fmt.numChannels,
138
      this.fmt.sampleRate,
139
      '16',
140
      alawmulaw.alaw.decode(this.data.samples),
141
      {container: this.correctContainer_()});
142
    if (bitDepthCode != '16') {
143
      this.toBitDepth(bitDepthCode);
144
    }
145
  }
146
147
  /**
148
   * Encode 16-bit wave file as 8-bit mu-Law.
149
   */
150
  toMuLaw() {
151
    this.assure16Bit_();
152
    /** @type {!Int16Array} */
153
    let output = new Int16Array(this.outputSize_());
154
    unpackArrayTo(this.data.samples, this.dataType, output);
155
    this.fromExisting_(
156
      this.fmt.numChannels,
157
      this.fmt.sampleRate,
158
      '8m',
159
      alawmulaw.mulaw.encode(output),
160
      {container: this.correctContainer_()});
161
  }
162
163
  /**
164
   * Decode a 8-bit mu-Law wave file into a 16-bit wave file.
165
   * @param {string} bitDepthCode The new bit depth of the samples.
166
   *    One of '8' ... '32' (integers), '32f' or '64' (floats).
167
   *    Optional. Default is 16.
168
   */
169
  fromMuLaw(bitDepthCode='16') {
170
    this.fromExisting_(
171
      this.fmt.numChannels,
172
      this.fmt.sampleRate,
173
      '16',
174
      alawmulaw.mulaw.decode(this.data.samples),
175
      {container: this.correctContainer_()});
176
    if (bitDepthCode != '16') {
177
      this.toBitDepth(bitDepthCode);
178
    }
179
  }
180
181
  /**
182
   * Change the bit depth of the samples.
183
   * @param {string} newBitDepth The new bit depth of the samples.
184
   *    One of '8' ... '32' (integers), '32f' or '64' (floats)
185
   * @param {boolean} changeResolution A boolean indicating if the
186
   *    resolution of samples should be actually changed or not.
187
   * @throws {Error} If the bit depth is not valid.
188
   */
189
  toBitDepth(newBitDepth, changeResolution=true) {
190
    /** @type {string} */
191
    let toBitDepth = newBitDepth;
192
    /** @type {string} */
193
    let thisBitDepth = this.bitDepth;
194
    if (!changeResolution) {
195
      if (newBitDepth != '32f') {
196
        toBitDepth = this.dataType.bits.toString();
197
      }
198
      thisBitDepth = '' + this.dataType.bits;
199
    }
200
    // If the file is compressed, make it
201
    // PCM before changing the bit depth
202
    this.assureUncompressed_();
203
    /**
204
     * The original samples, interleaved.
205
     * @type {!Array|!TypedArray}
206
     */
207
    let samples = this.getSamples(true);
208
    /**
209
     * The container for the new samples.
210
     * @type {!Float64Array}
211
     */
212
    let newSamples = new Float64Array(samples.length);
213
    // Change the bit depth
214
    changeBitDepth(samples, thisBitDepth, newSamples, toBitDepth);
215
    // Re-create the file
216
    this.fromExisting_(
217
      this.fmt.numChannels,
218
      this.fmt.sampleRate,
219
      newBitDepth,
220
      newSamples,
221
      {container: this.correctContainer_()});
222
  }
223
224
  /**
225
   * Convert the sample rate of the file.
226
   * @param {number} sampleRate The target sample rate.
227
   * @param {?Object} details The extra configuration, if needed.
228
   */
229
  toSampleRate(sampleRate, details={}) {
230
    this.validateResample_(sampleRate);
231
    /** @type {!Array|!TypedArray} */
232
    let samples = this.getSamples();
233
    /** @type {!Array|!Float64Array} */
234
    let newSamples = [];
235
    // Mono files
236
    if (samples.constructor === Float64Array) {
237
      newSamples = resample(samples, this.fmt.sampleRate, sampleRate, details);
238
    // Multi-channel files
239
    } else {
240
      for (let i = 0; i < samples.length; i++) {
241
        newSamples.push(resample(
242
          samples[i], this.fmt.sampleRate, sampleRate, details));
243
      }
244
    }
245
    // Truncate samples
246
    if (this.bitDepth !== '64' && this.bitDepth !== '32f') {
247
      // Truncate samples in mono files
248
      if (newSamples[0].constructor === Number) {
249
        truncateIntSamples(newSamples, this.dataType.bits);
250
      // Truncate samples in multi-channel files
251
      } else {
252
        for (let i = 0; i < newSamples.length; i++) {
253
          truncateIntSamples(newSamples[i], this.dataType.bits);
254
        }
255
      }
256
    }
257
    // Recreate the file
258
    this.fromExisting_(
259
      this.fmt.numChannels, sampleRate, this.bitDepth, newSamples,
260
      {'container': this.correctContainer_()});
261
  }
262
263
  /**
264
   * Validate the conditions for resampling.
265
   * @param {number} sampleRate The target sample rate.
266
   * @throws {Error} If the file cant be resampled.
267
   * @private
268
   */
269
  validateResample_(sampleRate) {
270
    if (!validateSampleRate(
271
        this.fmt.numChannels, this.fmt.bitsPerSample, sampleRate)) {
272
      throw new Error('Invalid sample rate.');
273
    } else if (['4','8a','8m'].indexOf(this.bitDepth) > -1) {
274
      throw new Error(
275
        'wavefile can\'t change the sample rate of compressed files.');
276
    }
277
  }
278
279
  /**
280
   * Make the file 16-bit if it is not.
281
   * @private
282
   */
283
  assure16Bit_() {
284
    this.assureUncompressed_();
285
    if (this.bitDepth != '16') {
286
      this.toBitDepth('16');
287
    }
288
  }
289
290
  /**
291
   * Uncompress the samples in case of a compressed file.
292
   * @private
293
   */
294
  assureUncompressed_() {
295
    if (this.bitDepth == '8a') {
296
      this.fromALaw();
297
    } else if (this.bitDepth == '8m') {
298
      this.fromMuLaw();
299
    } else if (this.bitDepth == '4') {
300
      this.fromIMAADPCM();
301
    }
302
  }
303
304
  /**
305
   * Return 'RIFF' if the container is 'RF64', the current container name
306
   * otherwise. Used to enforce 'RIFF' when RF64 is not allowed.
307
   * @return {string}
308
   * @private
309
   */
310
  correctContainer_() {
311
    return this.container == 'RF64' ? 'RIFF' : this.container;
312
  }
313
314
  /**
315
   * Set up the WaveFileCreator object based on the arguments passed.
316
   * This method only reset the fmt , fact, ds64 and data chunks.
317
   * @param {number} numChannels The number of channels
318
   *    (Integer numbers: 1 for mono, 2 stereo and so on).
319
   * @param {number} sampleRate The sample rate.
320
   *    Integer numbers like 8000, 44100, 48000, 96000, 192000.
321
   * @param {string} bitDepthCode The audio bit depth code.
322
   *    One of '4', '8', '8a', '8m', '16', '24', '32', '32f', '64'
323
   *    or any value between '8' and '32' (like '12').
324
   * @param {!Array|!TypedArray} samples
325
   *    The samples. Must be in the correct range according to the bit depth.
326
   * @param {?Object} options Optional. Used to force the container
327
   *    as RIFX with {'container': 'RIFX'}
328
   * @throws {Error} If any argument does not meet the criteria.
329
   * @private
330
   */
331
  fromExisting_(numChannels, sampleRate, bitDepthCode, samples, options={}) {
332
    let tmpWav = new WaveFileMetaEditor();
333
    Object.assign(this.fmt, tmpWav.fmt);
334
    Object.assign(this.fact, tmpWav.fact);
335
    Object.assign(this.ds64, tmpWav.ds64);
336
    Object.assign(this.data, tmpWav.data);
337
    this.newWavFile_(numChannels, sampleRate, bitDepthCode, samples, options);
338
  }
339
340
  /**
341
   * Return the size in bytes of the output sample array when applying
342
   * compression to 16-bit samples.
343
   * @return {number}
344
   * @private
345
   */
346
  outputSize_() {
347
    /** @type {number} */
348
    let outputSize = this.data.samples.length / 2;
349
    if (outputSize % 2) {
350
      outputSize++;
351
    }
352
    return outputSize;
353
  }
354
}
355